<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">报到管理</h1>
          <p class="mt-1 text-sm text-gray-600">管理学生报到状态、住宿分配、报到统计等相关事务</p>
        </div>
        <div class="flex items-center gap-3">
          <button
            @click="handleBatchAssignDormitory"
            :disabled="selectedStudents.length === 0"
            class="inline-flex items-center px-4 py-2 bg-purple-600 text-white text-sm font-medium rounded-lg hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <HomeIcon class="w-4 h-4 mr-2" />
            批量分配宿舍
          </button>
          <button
            @click="handleExportReport"
            class="inline-flex items-center px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
          >
            <DocumentArrowDownIcon class="w-4 h-4 mr-2" />
            导出报告
          </button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <UsersIcon class="h-8 w-8 text-blue-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总学生数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ totalStudents }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <CheckCircleIcon class="h-8 w-8 text-green-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">已报到</p>
            <p class="text-2xl font-semibold text-gray-900">{{ registeredStudents }}</p>
            <p class="text-xs text-green-600">{{ registrationRate }}%</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <HomeIcon class="h-8 w-8 text-purple-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">已分配宿舍</p>
            <p class="text-2xl font-semibold text-gray-900">{{ assignedDormitory }}</p>
            <p class="text-xs text-purple-600">{{ dormitoryRate }}%</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <ClockIcon class="h-8 w-8 text-yellow-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">未报到</p>
            <p class="text-2xl font-semibold text-gray-900">{{ unregisteredStudents }}</p>
            <p class="text-xs text-yellow-600">需要关注</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 报到趋势图表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
      <h2 class="text-lg font-medium text-gray-900 mb-4">报到趋势</h2>
      <div ref="chartContainer" class="h-64"></div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-6 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">学号/姓名</label>
          <input
            v-model="searchForm.keyword"
            type="text"
            placeholder="请输入学号或姓名"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">专业</label>
          <Listbox v-model="searchForm.major">
            <div class="relative">
              <ListboxButton class="relative w-full cursor-default rounded-lg bg-white py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <span class="block truncate">{{ searchForm.major || '请选择专业' }}</span>
                <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                  <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                </span>
              </ListboxButton>
              <transition
                leave-active-class="transition duration-100 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
              >
                <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                  <ListboxOption value="" class="relative cursor-default select-none py-2 pl-10 pr-4 text-gray-900 hover:bg-blue-100">
                    <span class="block truncate font-normal">全部专业</span>
                  </ListboxOption>
                  <ListboxOption
                    v-for="major in majors"
                    :key="major"
                    :value="major"
                    v-slot="{ active, selected }"
                    class="relative cursor-default select-none py-2 pl-10 pr-4"
                    :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                  >
                    <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                      {{ major }}
                    </span>
                    <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                      <CheckIcon class="h-5 w-5" aria-hidden="true" />
                    </span>
                  </ListboxOption>
                </ListboxOptions>
              </transition>
            </div>
          </Listbox>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">班级</label>
          <Listbox v-model="searchForm.class">
            <div class="relative">
              <ListboxButton class="relative w-full cursor-default rounded-lg bg-white py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <span class="block truncate">{{ searchForm.class || '请选择班级' }}</span>
                <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                  <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                </span>
              </ListboxButton>
              <transition
                leave-active-class="transition duration-100 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
              >
                <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                  <ListboxOption value="" class="relative cursor-default select-none py-2 pl-10 pr-4 text-gray-900 hover:bg-blue-100">
                    <span class="block truncate font-normal">全部班级</span>
                  </ListboxOption>
                  <ListboxOption
                    v-for="cls in classes"
                    :key="cls"
                    :value="cls"
                    v-slot="{ active, selected }"
                    class="relative cursor-default select-none py-2 pl-10 pr-4"
                    :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                  >
                    <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                      {{ cls }}
                    </span>
                    <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                      <CheckIcon class="h-5 w-5" aria-hidden="true" />
                    </span>
                  </ListboxOption>
                </ListboxOptions>
              </transition>
            </div>
          </Listbox>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">报到状态</label>
          <select
            v-model="searchForm.registrationStatus"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部状态</option>
            <option value="已报到">已报到</option>
            <option value="未报到">未报到</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">住宿状态</label>
          <select
            v-model="searchForm.dormitoryStatus"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部状态</option>
            <option value="已分配">已分配</option>
            <option value="未分配">未分配</option>
          </select>
        </div>
        <div class="flex items-end gap-2">
          <button
            @click="handleSearch"
            class="flex-1 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <MagnifyingGlassIcon class="w-4 h-4 mr-2 inline" />
            搜索
          </button>
          <button
            @click="handleReset"
            class="px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
          >
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 学生列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h2 class="text-lg font-medium text-gray-900">学生报到列表</h2>
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-500">共 {{ filteredStudents.length }} 名学生</span>
            <div class="flex items-center gap-2">
              <button
                @click="handleBatchRegister"
                :disabled="selectedStudents.length === 0"
                class="px-3 py-1.5 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <CheckCircleIcon class="w-4 h-4 mr-1 inline" />
                批量报到
              </button>
              <button
                @click="handleExport"
                class="px-3 py-1.5 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
              >
                <ArrowDownTrayIcon class="w-4 h-4 mr-1 inline" />
                导出
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left">
                <input
                  type="checkbox"
                  :checked="selectedStudents.length === filteredStudents.length && filteredStudents.length > 0"
                  @change="handleSelectAll"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">专业班级</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">报到状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">报到时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">住宿信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系方式</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="student in paginatedStudents" :key="student.id" class="hover:bg-gray-50">
              <td class="px-6 py-4">
                <input
                  type="checkbox"
                  :value="student.id"
                  v-model="selectedStudents"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="flex-shrink-0 h-10 w-10">
                    <div class="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                      <UserIcon class="h-6 w-6 text-gray-600" />
                    </div>
                  </div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">{{ student.name }}</div>
                    <div class="text-sm text-gray-500">{{ student.studentId }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">{{ student.major }}</div>
                <div class="text-sm text-gray-500">{{ student.class }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  :class="{
                    'bg-green-100 text-green-800': student.registrationStatus === '已报到',
                    'bg-red-100 text-red-800': student.registrationStatus === '未报到'
                  }"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ student.registrationStatus }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ student.registrationTime || '-' }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div v-if="student.dormitory" class="text-sm text-gray-900">
                  {{ student.dormitory.building }} {{ student.dormitory.roomNumber }}
                  <div class="text-xs text-gray-500">床位 {{ student.dormitory.bedNumber }}</div>
                </div>
                <span v-else class="text-sm text-gray-400">未分配</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">{{ student.phone }}</div>
                <div class="text-sm text-gray-500">{{ student.email }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center gap-2">
                  <button
                    v-if="student.registrationStatus === '未报到'"
                    @click="handleRegister(student)"
                    class="text-green-600 hover:text-green-900 transition-colors"
                    title="确认报到"
                  >
                    <CheckCircleIcon class="w-4 h-4" />
                  </button>
                  <button
                    v-if="!student.dormitory"
                    @click="handleAssignDormitory(student)"
                    class="text-purple-600 hover:text-purple-900 transition-colors"
                    title="分配宿舍"
                  >
                    <HomeIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleViewDetails(student)"
                    class="text-blue-600 hover:text-blue-900 transition-colors"
                    title="查看详情"
                  >
                    <EyeIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleEdit(student)"
                    class="text-yellow-600 hover:text-yellow-900 transition-colors"
                    title="编辑信息"
                  >
                    <PencilIcon class="w-4 h-4" />
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, filteredStudents.length) }} 条，共 {{ filteredStudents.length }} 条
          </div>
          <div class="flex items-center gap-2">
            <button
              @click="currentPage--"
              :disabled="currentPage === 1"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-sm font-medium text-gray-700">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button
              @click="currentPage++"
              :disabled="currentPage === totalPages"
              class="px-3 py-1 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 学生详情弹窗 -->
    <Dialog :open="showDetailsModal" @close="showDetailsModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            学生详情
          </DialogTitle>
          
          <div v-if="selectedStudent" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">学号</label>
                <p class="text-sm text-gray-900">{{ selectedStudent.studentId }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                <p class="text-sm text-gray-900">{{ selectedStudent.name }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">专业</label>
                <p class="text-sm text-gray-900">{{ selectedStudent.major }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">班级</label>
                <p class="text-sm text-gray-900">{{ selectedStudent.class }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">性别</label>
                <p class="text-sm text-gray-900">{{ selectedStudent.gender }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">联系电话</label>
                <p class="text-sm text-gray-900">{{ selectedStudent.phone }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                <p class="text-sm text-gray-900">{{ selectedStudent.email }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">报到状态</label>
                <span
                  :class="{
                    'bg-green-100 text-green-800': selectedStudent.registrationStatus === '已报到',
                    'bg-red-100 text-red-800': selectedStudent.registrationStatus === '未报到'
                  }"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ selectedStudent.registrationStatus }}
                </span>
              </div>
            </div>
            
            <div v-if="selectedStudent.dormitory">
              <label class="block text-sm font-medium text-gray-700 mb-1">住宿信息</label>
              <div class="bg-gray-50 rounded-lg p-3">
                <p class="text-sm text-gray-900">{{ selectedStudent.dormitory.building }} {{ selectedStudent.dormitory.roomNumber }}</p>
                <p class="text-xs text-gray-500">床位 {{ selectedStudent.dormitory.bedNumber }}</p>
              </div>
            </div>
            
            <div v-if="selectedStudent.emergencyContact">
              <label class="block text-sm font-medium text-gray-700 mb-1">紧急联系人</label>
              <div class="bg-gray-50 rounded-lg p-3">
                <p class="text-sm text-gray-900">{{ selectedStudent.emergencyContact.name }} ({{ selectedStudent.emergencyContact.relationship }})</p>
                <p class="text-xs text-gray-500">{{ selectedStudent.emergencyContact.phone }}</p>
              </div>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button
              @click="showDetailsModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              关闭
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 分配宿舍弹窗 -->
    <Dialog :open="showAssignModal" @close="showAssignModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            分配宿舍 - {{ selectedStudent?.name }}
          </DialogTitle>
          
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">选择楼宇</label>
              <Listbox v-model="assignForm.building">
                <div class="relative">
                  <ListboxButton class="relative w-full cursor-default rounded-lg bg-white py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <span class="block truncate">{{ assignForm.building || '请选择楼宇' }}</span>
                    <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                      <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                    </span>
                  </ListboxButton>
                  <transition
                    leave-active-class="transition duration-100 ease-in"
                    leave-from-class="opacity-100"
                    leave-to-class="opacity-0"
                  >
                    <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                      <ListboxOption
                        v-for="building in availableBuildings"
                        :key="building"
                        :value="building"
                        v-slot="{ active, selected }"
                        class="relative cursor-default select-none py-2 pl-10 pr-4"
                        :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                      >
                        <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                          {{ building }}
                        </span>
                        <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                          <CheckIcon class="h-5 w-5" aria-hidden="true" />
                        </span>
                      </ListboxOption>
                    </ListboxOptions>
                  </transition>
                </div>
              </Listbox>
            </div>
            
            <div v-if="assignForm.building">
              <label class="block text-sm font-medium text-gray-700 mb-2">可用宿舍</label>
              <div class="max-h-60 overflow-y-auto border border-gray-200 rounded-lg">
                <table class="min-w-full divide-y divide-gray-200">
                  <thead class="bg-gray-50">
                    <tr>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">宿舍号</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">楼层</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">空余床位</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                  </thead>
                  <tbody class="bg-white divide-y divide-gray-200">
                    <tr v-for="dormitory in availableDormitories" :key="dormitory.id" class="hover:bg-gray-50">
                      <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ dormitory.roomNumber }}</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ dormitory.floor }}楼</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ dormitory.type }}</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ dormitory.totalBeds - dormitory.occupiedBeds }}</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button
                          @click="handleConfirmAssign(dormitory)"
                          class="text-blue-600 hover:text-blue-900 transition-colors"
                        >
                          分配
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          
          <div class="flex justify-end gap-3 pt-4">
            <button
              @click="showAssignModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              取消
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useAppStore } from '../../stores/app'
import * as echarts from 'echarts'
import {
  Dialog,
  DialogPanel,
  DialogTitle,
  Listbox,
  ListboxButton,
  ListboxOptions,
  ListboxOption
} from '@headlessui/vue'
import {
  UsersIcon,
  CheckCircleIcon,
  HomeIcon,
  ClockIcon,
  DocumentArrowDownIcon,
  MagnifyingGlassIcon,
  ArrowDownTrayIcon,
  UserIcon,
  EyeIcon,
  PencilIcon,
  ChevronUpDownIcon,
  CheckIcon
} from '@heroicons/vue/24/outline'

// 使用stores
const appStore = useAppStore()

// 响应式数据
const searchForm = ref({
  keyword: '',
  major: '',
  class: '',
  registrationStatus: '',
  dormitoryStatus: ''
})

const showDetailsModal = ref(false)
const showAssignModal = ref(false)
const selectedStudents = ref([])
const selectedStudent = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const chartContainer = ref(null)

const assignForm = ref({
  building: ''
})

// 模拟数据
const students = ref([
  {
    id: 1,
    studentId: '2024001',
    name: '张三',
    gender: '男',
    major: '计算机科学与技术',
    class: '计科2024-1班',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    registrationStatus: '已报到',
    registrationTime: '2024-09-01 09:30',
    dormitory: {
      building: '1号楼',
      roomNumber: '101',
      bedNumber: 1
    },
    emergencyContact: {
      name: '张父',
      relationship: '父亲',
      phone: '13900139001'
    }
  },
  {
    id: 2,
    studentId: '2024002',
    name: '李四',
    gender: '女',
    major: '软件工程',
    class: '软工2024-1班',
    phone: '13800138002',
    email: 'lisi@example.com',
    registrationStatus: '已报到',
    registrationTime: '2024-09-01 10:15',
    dormitory: {
      building: '2号楼',
      roomNumber: '201',
      bedNumber: 1
    },
    emergencyContact: {
      name: '李母',
      relationship: '母亲',
      phone: '13900139002'
    }
  },
  {
    id: 3,
    studentId: '2024003',
    name: '王五',
    gender: '男',
    major: '电子信息工程',
    class: '电信2024-1班',
    phone: '13800138003',
    email: 'wangwu@example.com',
    registrationStatus: '未报到',
    registrationTime: null,
    dormitory: null,
    emergencyContact: {
      name: '王父',
      relationship: '父亲',
      phone: '13900139003'
    }
  },
  {
    id: 4,
    studentId: '2024004',
    name: '赵六',
    gender: '女',
    major: '计算机科学与技术',
    class: '计科2024-2班',
    phone: '13800138004',
    email: 'zhaoliu@example.com',
    registrationStatus: '已报到',
    registrationTime: '2024-09-02 08:45',
    dormitory: null,
    emergencyContact: {
      name: '赵母',
      relationship: '母亲',
      phone: '13900139004'
    }
  }
])

const dormitories = ref([
  {
    id: 1,
    roomNumber: '102',
    building: '1号楼',
    floor: 1,
    type: '4人间',
    totalBeds: 4,
    occupiedBeds: 1
  },
  {
    id: 2,
    roomNumber: '103',
    building: '1号楼',
    floor: 1,
    type: '4人间',
    totalBeds: 4,
    occupiedBeds: 0
  },
  {
    id: 3,
    roomNumber: '202',
    building: '2号楼',
    floor: 2,
    type: '6人间',
    totalBeds: 6,
    occupiedBeds: 2
  }
])

// 计算属性
const majors = computed(() => {
  return [...new Set(students.value.map(s => s.major))]
})

const classes = computed(() => {
  return [...new Set(students.value.map(s => s.class))]
})

const filteredStudents = computed(() => {
  let result = students.value
  
  if (searchForm.value.keyword) {
    result = result.filter(student => 
      student.name.includes(searchForm.value.keyword) ||
      student.studentId.includes(searchForm.value.keyword)
    )
  }
  
  if (searchForm.value.major) {
    result = result.filter(student => student.major === searchForm.value.major)
  }
  
  if (searchForm.value.class) {
    result = result.filter(student => student.class === searchForm.value.class)
  }
  
  if (searchForm.value.registrationStatus) {
    result = result.filter(student => student.registrationStatus === searchForm.value.registrationStatus)
  }
  
  if (searchForm.value.dormitoryStatus) {
    if (searchForm.value.dormitoryStatus === '已分配') {
      result = result.filter(student => student.dormitory)
    } else {
      result = result.filter(student => !student.dormitory)
    }
  }
  
  return result
})

const totalPages = computed(() => {
  return Math.ceil(filteredStudents.value.length / pageSize.value)
})

const paginatedStudents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredStudents.value.slice(start, end)
})

const totalStudents = computed(() => students.value.length)
const registeredStudents = computed(() => students.value.filter(s => s.registrationStatus === '已报到').length)
const unregisteredStudents = computed(() => students.value.filter(s => s.registrationStatus === '未报到').length)
const assignedDormitory = computed(() => students.value.filter(s => s.dormitory).length)

const registrationRate = computed(() => {
  return totalStudents.value > 0 ? Math.round((registeredStudents.value / totalStudents.value) * 100) : 0
})

const dormitoryRate = computed(() => {
  return totalStudents.value > 0 ? Math.round((assignedDormitory.value / totalStudents.value) * 100) : 0
})

const availableBuildings = computed(() => {
  return [...new Set(dormitories.value.map(d => d.building))]
})

const availableDormitories = computed(() => {
  if (!assignForm.value.building) return []
  return dormitories.value.filter(d => 
    d.building === assignForm.value.building && 
    d.occupiedBeds < d.totalBeds
  )
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.value = {
    keyword: '',
    major: '',
    class: '',
    registrationStatus: '',
    dormitoryStatus: ''
  }
  currentPage.value = 1
}

const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedStudents.value = filteredStudents.value.map(student => student.id)
  } else {
    selectedStudents.value = []
  }
}

const handleRegister = async (student) => {
  const index = students.value.findIndex(s => s.id === student.id)
  if (index > -1) {
    students.value[index].registrationStatus = '已报到'
    students.value[index].registrationTime = new Date().toLocaleString('zh-CN')
    appStore.showNotification(`${student.name} 报到成功`, 'success')
  }
}

const handleBatchRegister = async () => {
  if (selectedStudents.value.length === 0) return
  
  selectedStudents.value.forEach(studentId => {
    const index = students.value.findIndex(s => s.id === studentId)
    if (index > -1 && students.value[index].registrationStatus === '未报到') {
      students.value[index].registrationStatus = '已报到'
      students.value[index].registrationTime = new Date().toLocaleString('zh-CN')
    }
  })
  
  selectedStudents.value = []
  appStore.showNotification('批量报到成功', 'success')
}

const handleViewDetails = (student) => {
  selectedStudent.value = student
  showDetailsModal.value = true
}

const handleEdit = (student) => {
  appStore.showNotification('编辑功能开发中', 'info')
}

const handleAssignDormitory = (student) => {
  selectedStudent.value = student
  assignForm.value.building = ''
  showAssignModal.value = true
}

const handleConfirmAssign = async (dormitory) => {
  if (!selectedStudent.value) return
  
  // 找到第一个空闲床位
  const bedNumber = dormitory.occupiedBeds + 1
  
  // 更新学生信息
  const studentIndex = students.value.findIndex(s => s.id === selectedStudent.value.id)
  if (studentIndex > -1) {
    students.value[studentIndex].dormitory = {
      building: dormitory.building,
      roomNumber: dormitory.roomNumber,
      bedNumber: bedNumber
    }
  }
  
  // 更新宿舍入住数
  const dormitoryIndex = dormitories.value.findIndex(d => d.id === dormitory.id)
  if (dormitoryIndex > -1) {
    dormitories.value[dormitoryIndex].occupiedBeds++
  }
  
  showAssignModal.value = false
  appStore.showNotification(`成功为 ${selectedStudent.value.name} 分配宿舍`, 'success')
}

const handleBatchAssignDormitory = () => {
  if (selectedStudents.value.length === 0) return
  appStore.showNotification('批量分配宿舍功能开发中', 'info')
}

const handleExport = () => {
  const csvContent = [
    ['学号', '姓名', '专业', '班级', '报到状态', '报到时间', '宿舍', '联系电话'],
    ...filteredStudents.value.map(student => [
      student.studentId,
      student.name,
      student.major,
      student.class,
      student.registrationStatus,
      student.registrationTime || '',
      student.dormitory ? `${student.dormitory.building} ${student.dormitory.roomNumber}` : '',
      student.phone
    ])
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `学生报到列表_${new Date().toISOString().split('T')[0]}.csv`
  link.click()
  
  appStore.showNotification('导出成功', 'success')
}

const handleExportReport = () => {
  appStore.showNotification('报告导出功能开发中', 'info')
}

const initChart = () => {
  if (!chartContainer.value) return
  
  const chart = echarts.init(chartContainer.value)
  
  const option = {
    title: {
      text: '报到趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['累计报到人数', '当日报到人数'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['9/1', '9/2', '9/3', '9/4', '9/5', '9/6', '9/7']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '累计报到人数',
        type: 'line',
        data: [120, 280, 450, 580, 720, 850, 920],
        smooth: true,
        itemStyle: {
          color: '#3B82F6'
        }
      },
      {
        name: '当日报到人数',
        type: 'bar',
        data: [120, 160, 170, 130, 140, 130, 70],
        itemStyle: {
          color: '#10B981'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 生命周期
onMounted(async () => {
  await nextTick()
  initChart()
})
</script>